<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('修改活动')" />
    <th:block th:include="include :: datetimepicker-css" />
    <th:block th:include="include :: summernote-css" />
    <th:block th:include="include :: bootstrap-fileinput-css" />
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css" rel="stylesheet">
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-activity-edit" th:object="${lmActivity}">
            <input name="id" th:field="*{id}" type="hidden">
            <input id="p1" name="provinceName" th:field="*{provinceName}" type="hidden">
            <input id="c1" name="cityName" th:field="*{cityName}" type="hidden">
            <input id="d1" name="distName" th:field="*{distName}" type="hidden">
            <div class="form-group">
                <label class="col-sm-3 control-label">活动主题：</label>
                <div class="col-sm-8">
                    <input id="activityTitle" name="activityTitle" th:field="*{activityTitle}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">活动内容：</label>
                <div class="col-sm-8">
<!--                    <input type="hidden" class="form-control" th:field="*{activityPcontent}">
                    <div class="summernote" id="activityContent"></div>-->
                    <textarea id="activityPcontent" name="activityPcontent" th:field="*{activityPcontent}" cols="5" class="form-control"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="font-noraml">活动图片</label>
                <input name="activityPimages" th:field="*{activityPimages}" type="hidden">
                <div class="file-loading">
                    <input id="fileinput-demo-1" class="form-control file-upload" name="file" type="file" multiple data-min-file-count="1" data-theme="fas">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">活动发布：</label>
                <div class="col-sm-8">
                    <input style="width: 50%;float:left;" id="provinceName"  class="form-control" type="text">
                    <select class="selectpicker form-control"  onchange="initCity()" id="activityProvince" name="activityProvince">
                        <option  value="" >--省份--</option>
                    </select>
                    <input style="width: 50%;float:left;" id="cityName"  class="form-control" type="text">
                    <select class="selectpicker form-control"  onchange="initRegion()" id="activityCity" name="activityCity">
                        <option  value="">--城市--</option>
                    </select>
                    <input style="width: 50%;float:left;" id="distName"  class="form-control" type="text">
                    <select class="selectpicker form-control" onchange="initDist()" id="activityDist" name="activityDist">
                        <option   value="">--县区--</option>
                    </select>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">活动地点：</label>
                <div class="col-sm-8">
                    <input id="activityAddress" name="activityAddress" th:field="*{activityAddress}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">活动可参与人数：</label>
                <div class="col-sm-8">
                    <input id="activityMember" name="activityMember" th:field="*{activityMember}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">活动费用：</label>
                <div class="col-sm-8">
                    <input id="activityPrice" name="activityPrice" th:field="*{activityPrice}" class="form-control" type="text">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-3 control-label">活动截止日期：</label>
                <div class="col-sm-8">
                    <div class="input-group date">
                        <input id="endTime" name="endTime" th:value="${#dates.format(lmActivity.endTime, 'yyyy-MM-dd')}" class="form-control" placeholder="yyyy-MM-dd" type="text">
                        <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                    </div>
                </div>
            </div>
            <div class="form-group">    
                <label class="col-sm-3 control-label">目前已参与人数：</label>
                <div class="col-sm-8">
                    <input id="enjoyNum" readonly="true" name="enjoyNum" th:field="*{enjoyNum}" class="form-control" type="text">
                </div>
            </div>
        </form>
    </div>
    <th:block th:include="include :: footer" />
    <th:block th:include="include :: datetimepicker-js" />
    <th:block th:include="include :: summernote-js" />
    <th:block th:include="include :: bootstrap-fileinput-js" />
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>
    <script th:inline="javascript">
        var prefix = ctx + "lm/activity";

        $(document).ready(function(){

/*            $("#provinceName").html("value",$("#p1").val());
            $("#cityName").html("value",$("#c1").val());
            $("#distName").html("value",$("#d1").val());*/

            $("#provinceName").val($("#p1").val());
            $("#cityName").val($("#c1").val());
            $("#distName").val($("#d1").val());

            // 地区下拉框初始化
            $("#activityProvince").selectpicker({width:130, liveSearch: true, liveSearchPlaceholder: "搜索" });
            $("#activityCity").selectpicker({width:120, liveSearch: true, liveSearchPlaceholder: "搜索" });
            $("#activityDist").selectpicker({width:120, liveSearch: true, liveSearchPlaceholder: "搜索" });

            // 动态加载省份选项数据
            initSelectOptions("activityProvince","0");
        });// onReady

        /**
         * 动态生成select选项
         * @param selectId
         * @returns
         */
        function initSelectOptions(selectId,parentId) {
            var selectObj = $("#" + selectId);
            $.ajax({
                url : prefix+"/"+parentId,
                async : false,
                type : "GET",
                success : function(result) {

                    var configs = result.rows;
                    selectObj.find("option:not(:first)").remove();
                    for (var i in configs) {
                        var addressConfig = configs[i];
                        var optionValue = addressConfig.id;
                        var optionText = addressConfig.areaName;
                        selectObj.append(new Option(optionText, optionValue));
                    }
                    debugger;
                    // 刷新select
                    selectObj.selectpicker('refresh');
                },
                error : function(result) {
                    toastr.error('获取['+ parentId + ']信息失败，原因：' + result.errorMessage);
                }
            });// ajax
        }

        /**
         * 根据选择的省份动态初始化城市options
         * @returns
         */
        function initCity() {
            // 当省份变动时，初始化城市和清空县区和街道
            var provinceSel = $("#activityProvince").val();
            debugger;
            $("#provinceName").val($("#activityProvince option:selected").text());
            initSelectOptions("activityCity", provinceSel);
            $("#activityDist").find("option:not(:first)").remove();
            $("#activityDist").selectpicker('refresh');
            /* $("#street").find("option:not(:first)").remove();
             $("#street").selectpicker('refresh');*/
        }

        /**
         * 根据选择的城市动态初始化区域options
         * @returns
         */
        function initRegion() {
            // 选择城市
            var citySel = $("#activityCity").val();
            debugger;
            $("#cityName").val($("#activityCity option:selected").text());
            initSelectOptions("activityDist", citySel);
        }

        /**
         * 根据区域修改区域名称
         * @returns
         */
        function initDist() {
            $("#distName").val($("#activityDist option:selected").text());
        }

        var images = $("#activityPimages").val().split(",");
        $(document).ready(function () {
            debugger;
            $("#fileinput-demo-1").fileinput({
                'uploadUrl': '/common/upload',
                overwriteInitial: false,
                initialPreviewAsData: true,
                showRemove:true,
               /* showUpload:false,*/
                initialPreview: images
            })/*.on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");
            })*/
                .on("fileuploaded", function(event, data) {
                    debugger;
                    var fileName = data.response.url;  //文件上传成功返回的文件名，可返回自定义文件名
                    images.push(fileName);
                })/*.on('fileremoved', function (event, id, index) {
                $("input[name='" + event.currentTarget.id + "']").val('')
            }).on('filesuccessremove', function (event, previewId, extra) {
                for (var i = 0; i < List.length; i++) {
                    if (List[i].KeyID== data) {
                        delete List[i];
                    }
                }
            })*/;

           /* var List = new Array();//定义一个全局变量去接受文件名和id
            $("#fileinput-demo-1").on("fileuploaded", function (event, data, previewId, index) {
                debugger;
                var dataName = data.files[0].name;  //文件上传成功返回的文件名，可返回自定义文件名
                var fileName = data.response.url;  //文件上传成功返回的文件名，可返回自定义文件名
                List.push({ FileName: fileName, KeyID: previewId });
                images.push(dataName);
            });*/
            /* $("#fileinput-demo-1").on("filesuccessremove", function (event, data, previewId, index) {
                 debugger;
                 for (var i = 0; i < List.length; i++) {
                     if (List[i].KeyID== data) {
                         delete List[i];
                     }
                 }
             });*/
            $("#fileinput-demo-1").on("fileremoved", function (event, data, previewId, index) {
                debugger;
                var preview = previewId.split("_");
                delete images[preview[1]];
            });
           /* $("#fileinput-demo-1").on("filedelete", function (event, data, previewId, index) {
                debugger;
                for (var i = 0; i < List.length; i++) {
                    if (List[i].KeyID== data) {
                        delete List[i];
                    }
                }
            });*/

            $("#fileinput-demo-1").fileinput('_initFileActions');
        });

        $("#form-activity-edit").validate({
            focusCleanup: true
        });

        $("input[name='endTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });


        function submitHandler() {
            if ($.validate.form()) {
                uploadFile();
            }
        }

        function uploadFile() {
            debugger;
            var formData = new FormData();

            if($('#fileinput-demo-1')[0].files.length>0){
                formData.append('fileName', $("#fileinput-demo-1").val());
                for(var i=0;i<$('#fileinput-demo-1')[0].files.length;i++){
                    formData.append('files', $('#fileinput-demo-1')[0].files[i]);
                }
            }else{
                var activityPimages ="";
                for(var i=0;i<images.length;i++){
                    if(typeof(images[i]) != "undefined"){
                        if(i != images.length-1){
                            activityPimages +=images[i]+",";
                        }else{
                            activityPimages +=images[i];
                        }
                    }
                }
                formData.append('activityPimages',activityPimages);
            }
            formData.append('activityTitle',$("#activityTitle").val());
            formData.append('activityPcontent',$("#activityPcontent").val());
            formData.append('activityAddress',$("#activityAddress").val());
            formData.append('activityMember',$("#activityMember").val());
            formData.append('activityPrice',$("#activityPrice").val());
            formData.append('id',$("#id").val());
            formData.append('activityProvince',$("#activityProvince").val());
            formData.append('activityCity',$("#activityCity").val());
            formData.append('activityDist',$("#activityDist").val());
            formData.append('endTime',$("#endTime").val());
            $.ajax({
                url: prefix + "/edit",
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function(result) {
                    $.operate.successCallback(result);
                }
            });



            /*if($('#fileinput-demo-1')[0].files.length>0){
                formData.append('fileName', $("#fileinput-demo-1").val());
                formData.append('file', $('#fileinput-demo-1')[0].files[0]);
            }
            formData.append('bannerTitle',$("#bannerTitle").val())
            formData.append('id',$("#id").val())
            $.ajax({
                url: prefix + "/edit",
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                dataType: "json",
                success: function(result) {
                    $.operate.successCallback(result);
                }
            });*/
        }


        $("input[name='reviewTime']").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });

        $(function() {
            $('.summernote').each(function(i) {
                $('#' + this.id).summernote({
                    lang: 'zh-CN',
                    callbacks: {
                        onChange: function(contents, $edittable) {
                            $("input[name='" + this.id + "']").val(contents);
                        },
                        onImageUpload: function(files) {
							var obj = this;
							var data = new FormData();
							data.append("file", files[0]);
							$.ajax({
								type: "post",
								url: ctx + "common/upload",
								data: data,
								cache: false,
								contentType: false,
								processData: false,
								dataType: 'json',
								success: function(result) {
									if (result.code == web_status.SUCCESS) {
										$('#' + obj.id).summernote('insertImage', result.url);
									} else {
										$.modal.alertError(result.msg);
									}
								},
								error: function(error) {
									$.modal.alertWarning("图片上传失败。");
								}
							});
						}
                    }
                });
                var content = $("input[name='" + this.id + "']").val();
                $('#' + this.id).summernote('code', content);
            })
        });
    </script>
</body>
</html>